<template>
    <el-steps class="mb-4" :space="200" :active="active" simple>
        <el-step title="组卷配置" :icon="EditPen" />
        <el-step title="考试权限" :icon="Lock" />
        <el-step title="补充配置" :icon="Setting" />
    </el-steps>
    <div style="margin-top: 12px">
        <el-button v-if="active > 0" @click="prev" size="large" style="float: left;">上一步</el-button>
        <el-button type="primary" v-if="active < 2" @click="next" size="large" class="rightButton">下一步</el-button>
        <el-button type="primary" v-else @click="submit" size="large" class="rightButton">&nbsp;提交&nbsp;</el-button>
    </div>

    <!-- 组卷配置 -->
    <div v-if="active == 0" style="margin-top: 70px;">
        <el-card>
            <el-card>
                <h4>题目列表</h4>
                <span style="float: right; color: red; font-weight: bold;">试卷总分:{{ examScores }}</span>
                <el-button style="margin: 15px 0;" type="primary" @click='fetchQuestions'> + &nbsp;添加试题</el-button>
            </el-card>

            <el-table :data="state.tableData2" style="width: 100%">
                <el-table-column label="序号" type="index" width="60px" />
                <el-table-column prop="quContent" label="题目内容" />
                <el-table-column prop="quType" label="题目类型">
                    <template v-slot="scope">
                        <span>{{ questionTypes[scope.row.quType] }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="单题分数">
                    <template v-slot="scope">
                        <el-input size="large" v-model="scope.row.score" />
                    </template>
                </el-table-column>

                <el-table-column label="操作">
                    <template v-slot="scope">
                        <el-button type="danger" :icon="Delete" circle size="large" @click="removeRow(scope.$index)" />
                    </template>
                </el-table-column>
            </el-table>

            <el-dialog v-model="dialogTableVisible" title="添加题目" center style="width:80%"
                :before-close="handleDialogClose">
                <div style="margin-bottom: 20px;">
                    <el-select clearable v-model="state.questionType" placeholder="请选择题目类型"
                        style="width: 150px; margin-right: 10px;" size="large">
                        <el-option label="单选题" value="1"></el-option>
                        <el-option label="多选题" value="2"></el-option>
                        <el-option label="判断题" value="3"></el-option>
                        <el-option label="简答题" value="4"></el-option>
                    </el-select>
                    <el-select clearable v-model="state.questionBank" placeholder="请选择题库"
                        style="width: 150px; margin-right: 10px;" size="large">
                        <el-option v-for="bank in banks" :key="bank.bankId" :label="bank.bankName"
                            :value="bank.bankName" />
                    </el-select>
                    <el-input v-model="state.questionContent" placeholder="题目内容"
                        style="width: 200px; margin-right: 10px;" @blur="fetchQuestions" @keyup.enter="fetchQuestions"
                        size="large" />
                    <el-button type="primary" size="large" style="float: right;" @click="confirmSelection">{{ confirm
                        }}</el-button>
                </div>
                <el-table :data="state.questionData" border style="width: 100%" header-background="#f2f3f4"
                    @selection-change="handleSelectionChange" tooltip-effect="dark">
                    <el-table-column type="selection" width="60" />
                    <el-table-column prop="quType" label="题目类型">
                        <template v-slot="scope">
                            <span>{{ questionTypes[scope.row.quType] }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="quContent" label="题目内容" />
                    <el-table-column prop="level" label="难度">
                        <template v-slot="scope">
                            <span>{{ difficultyLevels[scope.row.level] }}</span>
                        </template>
                    </el-table-column>

                    <el-table-column prop="quBankName" label="所属题库" />
                    <el-table-column prop="createPerson" label="创建人" />
                    <el-table-column prop="createTime" label="创建时间" />
                </el-table>

                <!-- 分页查询 -->
                <div class="demo-pagination-block">
                    <div class="demonstration"></div>
                    <el-pagination v-model:current-page="state.pageNo" v-model:page-size="state.pageSize"
                        :page-sizes="[5, 10, 15, 20]" :page-size="size" :disabled="disabled" :background="background"
                        layout="total, sizes, prev, pager, next, jumper" :total="state.total"
                        @size-change="handleSizeChange" @current-change="handleCurrentChange">
                    </el-pagination>
                </div>
            </el-dialog>
        </el-card>
    </div>

    <!-- 考试权限 -->
    <div v-else-if="active == 1" style="margin-top: 70px;">
        <el-card>
            <el-radio-group v-model="radio">
                <el-radio value="1" size="large" border class="marginButton">完全公开</el-radio>
                <el-radio value="2" size="large" border class="marginButton">需要密码</el-radio>
            </el-radio-group>
            <div v-if="radio == '1'">
                <el-alert v-if="showAlert" title="完全公开，任何人都可以进行考试！" type="warning" @close="showAlert = false" />
            </div>
            <div v-if="radio == '2'">
                <el-alert v-if="showAlert" title="需要密码，知道密码的人员才可以考试！" type="warning" @close="showAlert = false" />
                <el-input v-model="examPassword" style="width: 240px ;margin-top: 20px;" type="password"
                    placeholder="请输入密码" show-password size="large" />
            </div>
        </el-card>
    </div>

    <!-- 补充配置 -->
    <div v-else style="margin-top: 70px;">
        <el-card>
            <el-form :model="additionalConfig" :rules="rules" ref="form" label-width="120px">
                <el-form-item label="考试名称" prop="examName" required>
                    <el-input v-model="additionalConfig.examName" placeholder="请输入考试名称" size="large" />
                </el-form-item>
                <el-form-item label="考试描述">
                    <el-input v-model="additionalConfig.examDesc" placeholder="请输入考试描述" size="large" />
                </el-form-item>
                <el-form-item label="总分数" prop="examScores">
                    <el-input-number v-model="examScores" :disabled="true" size="large" />
                </el-form-item>
                <el-form-item label="及格分数" prop="passingScore" required>
                    <el-input-number v-model="additionalConfig.passingScore" :min="1" size="large" />
                </el-form-item>
                <el-form-item label="考试时长(分钟)" prop="examDuration" required>
                    <el-input-number v-model="additionalConfig.examDuration" :min="1" size="large" />
                </el-form-item>
                <el-form-item label="考试开始时间">
                    <el-date-picker v-model="additionalConfig.startTime" type="date" placeholder="考试开始时间"
                        size="large" />
                </el-form-item>
                <el-form-item label="考试结束时间">
                    <el-date-picker v-model="additionalConfig.endTime" type="date" placeholder="考试结束时间" size="large" />
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>

<script setup lang="ts">
import { EditPen, Lock, Setting, Delete } from '@element-plus/icons-vue'
import { ElMessageBox } from 'element-plus'
import { ref, reactive, inject, onMounted, watch, computed } from 'vue'
import {
    getExamInfoById,
    getQuestionById,
    getQuestionBank,
    getQuestion,
    updateExamInfo
} from '@/api/examControl/UpdateExam'
import { useRouter, useRoute } from 'vue-router';
const router = useRouter()
const route = useRoute()
const confirm = ref('确认0项')
const dialogTableVisible = ref(false)
const state = reactive({
    questionData: [],
    selectedRows: [],
    pageNo: 1,
    pageSize: 10,
    total: 0,
    questionType: '',
    questionBank: '',
    questionContent: '',
    tableData2: []
})
const banks = ref([])
const active = ref(0);
const radio = ref('1')
const examPassword = ref('')
const showAlert = ref(true)
const questionTypes = { 1: '单选题', 2: '多选题', 3: '判断题', 4: '简答题' }
const difficultyLevels = { 1: '简单', 2: '普通', 3: '困难' }

const examId = route.params.examId
//计算总分
const examScores = computed(() => {
    return state.tableData2.reduce((total, item) => {
        const score = parseFloat(item.score);
        return total + (isNaN(score) ? 0 : score);
    }, 0);
});
const additionalConfig = reactive({
    examName: '',
    examDesc: '',
    passingScore: 0,
    examDuration: 0,
    startTime: '',
    endTime: '',
    status: ''
})

const rules = reactive({
    examName: [{ required: true, message: '请输入考试名称', trigger: 'blur' }],
    passingScore: [{ required: true, message: '请输入及格分数', trigger: 'blur' }],
    examDuration: [{ required: true, message: '请输入考试时长', trigger: 'blur' }]
})

onMounted(async () => {
    await fetchExamInfo()
    await fetchBanks()
})

async function fetchExamInfo() {
    // 获取考试信息
    const  {data}  = await getExamInfoById(examId)

    Object.assign(additionalConfig, data.data);

    examPassword.value = data.data.password;
    // 解析 scores 字段为数组
    const scoresArray = data.data.scores.split(',').map(score => parseInt(score, 10));
    // 获取题目 IDs
    const questionIds = data.data.questionIds.split(',').map(id => parseInt(id, 10));
    radio.value = data.data.type == 1 ? '1' : '2'

    // 遍历每个题目 ID，获取题目信息
    for (let i = 0; i < questionIds.length; i++) {
        const id = questionIds[i];
        const  {data}  = await getQuestionById(id);
        state.tableData2.push({
            quId: id,
            quContent: data.data.questionContent,
            quType: data.data.questionType,
            score: scoresArray[i]
        });
    }
}


async function fetchBanks() {
    let { data } = await getQuestionBank()
    banks.value = data.data
}

const next = () => {
    if (active.value < 2) {
        active.value++
    }
}
const prev = () => {
    if (active.value > 0) {
        active.value--
    }
}
// 监听的变化
watch(() => [state.questionType, state.questionBank], () => {
    fetchQuestions();
});
function handleSelectionChange(val) {
    state.selectedRows = val;
    confirm.value = `确认${state.selectedRows.length}项`
}

async function fetchQuestions() {
    try {
        state.questionType = state.questionType || '';
        state.questionBank = state.questionBank || '';
        state.questionContent = state.questionContent || '';
        const { data } = await getQuestion(state.questionType, state.questionBank, state.questionContent, state.pageNo, state.pageSize);
        state.questionData = data.data.questions;
        state.total = data.data.total;
        dialogTableVisible.value = true;
    } catch (error) {
        console.error('获取试题数据失败', error)
    }
}

function handleCurrentChange(pageNo: number) {
    state.pageNo = pageNo;
    fetchQuestions()
}

function handleSizeChange(pageSize: number) {
    state.pageSize = pageSize;
    fetchQuestions()
}


const handleDialogClose = (done) => {
    state.pageNo = 1
    state.pageSize = 10
    state.questionType = '';
    state.questionBank = '';
    state.questionContent = '';
    done();
};

const confirmSelection = () => {
    state.tableData2.push(...state.selectedRows.map(row => ({
        quId: row.id,
        quContent: row.quContent,
        quType: row.quType,
        score: '1'
    })));
    dialogTableVisible.value = false;
};
const submit = async () => {
    try {
        let response;

        const commonParams = {
            startTime: additionalConfig.startTime,
            endTime: additionalConfig.endTime,
            examName: additionalConfig.examName,
            examDesc: additionalConfig.examDesc,
            examDuration: additionalConfig.examDuration,
            passScore: additionalConfig.passingScore,
            status: additionalConfig.status,
            type: radio.value,
            examId: examId,
            totalScore: examScores.value,
            password: examPassword.value,
        };
        const questionIds = state.tableData2.map(item => item.quId).join(',');
        const scores = state.tableData2.map(item => item.score).join(',');
        const params = {
            ...commonParams,
            questionIds,
            scores,
        };
        response = await updateExamInfo(params)
        if (response.data.status == 200) {
            // 提交成功
            console.log("更新考试成功");
        } else {
            // 提交失败
            console.log("更新考试失败");
        }
    } catch (error) {
        console.error('更新考试失败', error);
    }
    router.push({ path: `/home/examManage` });
};

function removeRow(index: number) {
    state.tableData2.splice(index, 1);
}
</script>

<style scoped>
.rightButton
{
    float: right;
}

.demo-pagination-block
{
    margin-top: 20px;
    text-align: right;
}

.marginButton
{
    margin-bottom: 30px;
}
</style>
